#include "queue.h"

queue *queue_create()
{
    queue_node *N = (queue_node *)malloc(sizeof(queue_node));
    N->next = NULL;
    N->data = 0;
    queue *S = (queue *)malloc(sizeof(queue));
    S->num = 0;
    S->node = N;

    return S;
}

void queue_push(queue *S, int data)
{
    if (NULL == S) {
        printf("无效队列.\n");
        return ;
    }

    queue_node *new = (queue_node *)malloc(sizeof(queue_node));

    new->data = data;
    new->next = S->node->next;
    S->node->next = new;
    S->num++;
}


int queue_pop(queue *S)
{
    if (NULL == S) {
        printf("无效队列.\n");
        return -1;
    }

    if (S->num == 0) {
        printf("空队列.\n");
        return -1;
    }

    queue_node *node = S->node->next;
    queue_node *cur;

    while(node->next != NULL)
    {
        cur = node;
        node = node->next;
    }

    int data = node->data;
    free(node);
    cur->next = NULL;
    S->num--;

    return data;
}

queue1 *queue_create1()
{
    queue_node1 *N = (queue_node1 *)malloc(sizeof(queue_node1));
    N->next = NULL;
    N->data = 0;
    queue1 *S = (queue1 *)malloc(sizeof(queue1));
    S->num = 0;
    S->node = N;
    S->newest = N;

    return S;
}

void queue_push1(queue1 *S, int data)
{
    if (NULL == S) {
        printf("无效队列.\n");
        return ;
    }

    queue_node1 *new = (queue_node1 *)malloc(sizeof(queue));
    new->data = data;
    new->next = NULL;

    S->newest->next = new;
    S->newest = new;
    S->num++;
}

int queue_pop1(queue1 *S)
{
    if (NULL == S) {
        printf("无效队列.\n");
        return -1;
    }

    if (S->node->next == NULL) {
        printf("空队列.\n");
        return -1;
    }

    queue_node1 *n = S->node->next;
    S->node->next = n->next;

    int data = n->data;
    free(n);

    return data;
}

